package com.jd.dict.helper;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;

/**
 * @Description:
 * @Auther: liuhaiming
 * @Date: 2019/8/26 21:55
 */
public class FreemarkerHelper {
    public static void replaceTemplate(String templateFilePath, String descFilePath, Object dataMap) {
        // step1 创建freeMarker配置实例
        Configuration configuration = new Configuration();
        Writer out = null;
        try {
            File templateFile = new File(templateFilePath);

            // step2 获取模版路径
            configuration.setDirectoryForTemplateLoading(templateFile.getParentFile());

            // step4 加载模版文件
            Template template = configuration.getTemplate(templateFile.getName());

            // step5 生成数据
            File docFile = new File(descFilePath);
            if (!docFile.getParentFile().exists()) {
                docFile.getParentFile().mkdirs();
            }

            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));

            // step6 输出文件
            template.process(dataMap, out);
            System.out.println(templateFilePath + "文件创建成功 !");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}